<template>
  <t-config-provider :global-config="{ classPrefix: 't' }">
    <reference path="./shims-vue.d.ts"/>
    <div style="position: absolute;right: 0.5em;top: 0.75em;z-index: 1024">
      <t-space size="0">
        <i class="iconfont icon-heiyemoshi theme-button theme-button-dark"
           @click="SetThemeDark"/>
        <i class="iconfont icon-qingbaitian theme-button theme-button-light"
           @click="SetThemeLight"/>
      </t-space>
    </div>
    <router-view/>
  </t-config-provider>
</template>

<script lang="ts" setup>
import {getDefaultStore} from "./store/modules/default";
import {onBeforeMount} from "vue";
import {curTimeUnix} from "./tool/time";
import {useRouter} from "vue-router";
import api from "./api/api";
import {getUserStore} from "./store/modules/user";

const defaultStore = getDefaultStore()
const userStore = getUserStore()

const router = useRouter()
const SetThemeDark = () => {
  document.documentElement.setAttribute('theme-mode', 'dark');
  window.localStorage.setItem("theme-mode", "dark")
}
const SetThemeLight = () => {
  document.documentElement.removeAttribute('theme-mode');
  window.localStorage.removeItem("theme-mode")
}

const RefreshToken = async () => {
  if (curTimeUnix() > defaultStore.tokenExpirationTime) {
    return
  }
  let res = await api.User.RefreshToken()
  if (res != null) {
    defaultStore.updateToken(res.data) //更新token
  }
}

const GetProfile = async () => {
  if (curTimeUnix() > defaultStore.tokenExpirationTime) {
    return
  }
  let res = await api.User.Profile()
  if (res != null) {
    userStore.updateProfile(res.data)
  }
}

// verifyToken 验证当前token是否过期
const verifyToken = async () => {
  if (curTimeUnix() > defaultStore.tokenExpirationTime) {
    defaultStore.updateToken("") //更新token为空
    await router.push({
      path: '/login', //跳转到登录页
    })
    return
  } else {
    if (curTimeUnix() + 600 >= defaultStore.tokenExpirationTime) {
      await RefreshToken()
    }
  }
  await GetProfile()
}

// @ts-ignore
onBeforeMount(async () => {
  defaultStore.updateToken(window.localStorage.getItem("token") || '')
  if ("dark" === window.localStorage.getItem("theme-mode") || "") {
    SetThemeDark()
  }
  setTimeout(() => {
    verifyToken()
    RefreshToken()
    setInterval(() => {
      verifyToken()
    }, 1000 * 60)
  }, 300)
})
</script>